package com.wzh.glsc.order.interceptor;

import com.wzh.common.constant.AuthServerConstant;
import com.wzh.common.vo.MemberVo;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author xiaoming
 * @PackageName:com.wzh.glsc.cart.config
 * @ClassName:@{NAME}
 * @Description: 执行方法前 拦截请求 判断用户的登录状态
 * @date:@{DATE}@{TIME}
 */
//拦截器必须实现 HandlerInterceptor 接口
//@Component // 这里不能直接放在容器中，要注册拦截器到mvc中
public class OrderInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberVo> toThreadLocal=new ThreadLocal<>();

    /**
     *  目标方法执行之前
     * @param request
     * @param response
     * @param handler
     * @return return true放行   return false 不放行
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //TODO 为什么这里报错后进入了多次？
        HttpSession session=request.getSession();
        MemberVo loginUser =new MemberVo();
        if(session.getAttribute(AuthServerConstant.LOGIN_USEER)!=null){
            loginUser = (MemberVo) session.getAttribute(AuthServerConstant.LOGIN_USEER);
            //放入共享线程中
            toThreadLocal.set(loginUser);
            return true;
        }
        request.getSession().setAttribute("msg","请先登录！");
        response.sendRedirect("http://auth.gulimall.com/login.html");
        return false;
    }

}
